# -*- coding: utf-8 -*-
import sys
import configparser
import redis
import pickle
import time

class RedisAdapter:

    config = ''  # Refer to config.ini
    redis_conn = ''  # Refer to Instance of redis connection

    def __init__(self):

        self.config = configparser.ConfigParser()
        self.config.read("config.ini")

        try:
            redis_host = self.config.get("redis", "host")
            redis_port = self.config.get("redis", "port")
            redis_db = self.config.getint("redis", "db")
            self.redis_conn = redis.Redis(host=redis_host, port=redis_port, db=redis_db)
        except Exception as e:
            print("Unabled to connect Redis, Please check redis configuration.\n", e)
            sys.exit()

    # Read Redis Data
    def get(self, name, key):
        return pickle.loads(self.redis_conn.hget(name, key))

    # Save Redis Data
    def set(self, name, key, value):
        self.redis_conn.hset(name, key, pickle.dumps(value))

    # Delete Redis Data
    def evict(self, name, keys):
        self.redis_conn.hdel(name, keys)

    # Close Redis Connection
    def close(self):
        self.redis_conn.shutdown()

if __name__ == '__main__':
    rds = RedisAdapter()
    for t in range(1,10):
        ct = time.time()
        region = "users"
        user = {'name':"Winter Lau",'age':1}
        print("result=",user,type(user))
        rds.set(region, 2, user)
        user = rds.get(region, 2)
        print("result=",user,type(user))
        print("Time Used = ",(time.time()-ct))